package com.tzy.nowcoder.leetcode;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

public class TheSumOfTwoNumbers {
    /**
     *  new一个HashMap,指定初始容量,避免扩容带来的性能损耗,
     *  将数组的第一个元素存入map,
     *  循环判断map里用没有 nums[i]-target
     *  有的话就返回数组 nums[i],map.get(target-nums[i])
     *  没有就往map里存入nums[i]
     *  继续循环
     * @param nums
     * @param target
     * @return
     */
    public int[] theSumOfTwoNumbers(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
//        map.put(nums[0],0);
        int len = nums.length;
        int[] index = new int[2];
        for (int i = 0; i < len; ++i) {
            int another = target - nums[i];

            if(map.containsKey(another)){
//                index = new int[]{map.get(another), i};
                index[0] = map.get(another);
                index[1] = i;
//                System.out.println("index="+index);
                return index;
            }
            map.put(nums[i],i);
        }

        return new int[0];
    }
    @Test
    public void test() {
        int[] nums ={3,2,4};
        int target = 6;
        for (int i:theSumOfTwoNumbers(nums,target)){
            System.out.println(i);
        }

    }







}
